package org.littlesun.management.address;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import lombok.AllArgsConstructor;

@AllArgsConstructor
public class AddressSuggester {

	private List<City> cities;
	
	public AddressSuggester(City... cities) {
		this(Arrays.asList(cities));
	}
	
	public List<String> getSuggestions(String text) {
		text = text.trim();
		MatchResult matchResult = new CityZoneMatcher(cities).match(text);
		if (matchResult.isSuccess() == false) {
			return matchResult.getSuggestions();
		}
		CityZone cityZone = (CityZone) matchResult.getMatchedObject();
		text = matchResult.getTextAfterMatch();
		if (text.trim().isEmpty()) {
			MatchResult roadMatch = new RoadMatcher(matchResult, cityZone).match(text);
			List<String> suggestions = new ArrayList<String>(matchResult.getSuggestions());
			suggestions.addAll(roadMatch.getSuggestions());
			return suggestions;
		}
		MatchResult roadMatch = new RoadMatcher(matchResult, cityZone).match(text);
		if (roadMatch.isSuccess() == false) {
			List<String> suggestions = new ArrayList<String>(matchResult.getSuggestions());
			if (cityZone.getZone() == null) {
				for(Zone zone : cityZone.getCity().getZones()) {
					suggestions.add(zone.getName());
				}
			}
			suggestions.addAll(roadMatch.getSuggestions());
		}
		text = roadMatch.getTextAfterMatch();
		MatchResult miscNosMatch = new MiscNosMatcher(roadMatch).match(text);
		if (miscNosMatch.isSuccess() == false) {
			return miscNosMatch.getSuggestions();
		}
		return Collections.emptyList();
	}

}
